package com.hspedu.list_;

import java.util.Iterator;
import java.util.LinkedList;

/**
 * @author DL5O
 * @version 1.0
 */
@SuppressWarnings("all")
public class LinkedListCRUD {

    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();
        linkedList.add(1);
        linkedList.add(2);
        linkedList.add(3);

        System.out.println("linkedList = " + linkedList);//[1, 2, 3]
        linkedList.remove();//删除第一个节点
//        linkedList.remove(1);//删除第二个节点
//        linkedList.remove(new Integer(1));//指定删除
        System.out.println(linkedList);//[2, 3]

        //修改某个节点对象
        linkedList.set(1,999);
        System.out.println(linkedList);//[2, 999]

        //得到某个节点对象
        Object o = linkedList.get(1);
        System.out.println(o);

        //因为linkedList实现了 list接口，所以它的遍历方式可以是增强for或者是迭代器
        Iterator iterator = linkedList.iterator();
        while(iterator.hasNext()){
            Object next = iterator.next();
            System.out.print(next+" ");
        }
        //2 999
        System.out.println();
        //源码阅读
        /*
            1.new 一个LinkedList后，调用它的无参构造器
                public LinkedList() {}
            2.这时linkedlist 的属性 first = null, last = null;
            3.执行
                public boolean add(E e) {
                    linkLast(e);
                    return true;
                }
            4.这时把插入的元素，插入到链表的尾部
                void linkLast(E e) {
                    final Node<E> l = last;
                    final Node<E> newNode = new Node<>(l, e, null);
                    last = newNode;
                    if (l == null)
                        first = newNode;
                    else
                        l.next = newNode;
                    size++;
                    modCount++;
                }
         */


        /*
            删除remove的源码
            1.
            public E remove() {
                return removeFirst();
            }
            2.执行
            public E removeFirst() {
                final Node<E> f = first;
                if (f == null)
                    throw new NoSuchElementException();
                return unlinkFirst(f);
            }

            3.执行 unlinkLast，将 f 指向的双向链表的第一个结点拿掉(删除)
            private E unlinkLast(Node<E> l) {
                // assert l == last && l != null;
                final E element = l.item;
                final Node<E> prev = l.prev;
                l.item = null;
                l.prev = null; // help GC
                last = prev;
                if (prev == null)
                    first = null;
                else
                    prev.next = null;
                size--;
                modCount++;
                return element;
            }
         */

    }
}
